package com.wanmei.controller.user;

import com.wanmei.pojo.JsonResult;
import com.wanmei.pojo.Role;
import com.wanmei.pojo.User;
import com.wanmei.service.RoleService;
import com.wanmei.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService rolesService;


    @RequestMapping("/info/login.json")
    @ResponseBody
    public JsonResult loginCheckout(User user, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] boxs = req.getParameterValues("checkBoxName");
        if (req.isRequestedSessionIdFromURL()) {
            HttpSession session = req.getSession();
            if (session != null) {
                session.invalidate();
            }
        }
        JsonResult result = new JsonResult();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        if (user.getUsername() == null || user.getUsername() == "") {
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return null;
        } else {
            //判断是否输入 是否记住登录，如果选中的时候，就代表为box的值就大于0
            if (boxs != null && boxs.length > 0) {
                token.setRememberMe(true);
            } else {
                token.setRememberMe(false);
            }
            try {
                subject.login(token);
                if (subject.isAuthenticated()) {
                    String username = (String) subject.getPrincipal();
                    User user1 = userService.getUserByUserName(username);
                    Role roles = rolesService.getRoleByRoleId(user1.getRid());
                    req.getSession().setAttribute("role",roles.getName());
                    req.getSession().setMaxInactiveInterval(2*60*60);
                    if (subject.hasRole("admin")||subject.hasRole("system")){
                    result.setCode(1);}
                    else {
                        result.setCode(3);
                    }
                }
            } catch (UnknownAccountException e) {
                result.setCode(2);
                result.setMsg("账号或者密码错误！");
            } catch (IncorrectCredentialsException e) {
                result.setCode(2);
                result.setMsg("账号或者密码错误");
            } catch (ExcessiveAttemptsException e) {
                result.setCode(2);
                result.setMsg("登录错误次数太多，已经被锁定！十分钟后在登录！");
            } catch (AuthenticationException e) {
                result.setCode(2);
                result.setMsg("账号或者密码错误！");
            } catch (UnauthorizedException e) {
                result.setCode(2);
                result.setMsg("没有权限!管理员才允许进入！");
            }catch (AuthorizationException e){
                result.setCode(2);
                result.setMsg("没有权限!管理员才允许进入！");
            }
        }
        return result;
    }

    /**
     * 登录成功
     *
     * @return
     */
    @RequestMapping("/success.do")
    public String successLogin() {
        return "index";
    }

}
